﻿using System.Collections.Generic;
using UnityEngine;


public class MaterialRes
{
    public string name;
    public string path;
    public Material material;
}

public class MaterialManager
{
    private static readonly Dictionary<string, MaterialRes> _materialDic = new Dictionary<string, MaterialRes>();

    /// <summary>
    /// 加载材质
    /// </summary>
    public static MaterialRes LoadMaterial(string materialPath, string materialName)
    {
        if (string.IsNullOrWhiteSpace(materialPath) || string.IsNullOrEmpty(materialPath))
        {
            Debug.LogError("材质路径为空");
            return null;
        }


        if (string.IsNullOrWhiteSpace(materialName) || string.IsNullOrEmpty(materialName))
        {
            Debug.LogError("材质名字为空");
            return null;
        }


        if (_materialDic.ContainsKey(materialName))
        {
            MaterialRes materialRes = _materialDic[materialName];
            if (!materialRes.path.Equals(materialPath))
            {
                Debug.LogError("非相同路径下的材质，请检查");
                return null;
            }

            return materialRes;
        }
        else
        {
            MaterialRes materialRes = new MaterialRes();
            materialRes.path = materialPath;
            materialRes.name = materialName;
            materialRes.material = ResourceManager.Instance.LoadMaterial(materialPath, materialName);
            ;
            _materialDic.Add(materialName, materialRes);
            return _materialDic[materialName];
        }
    }

    /// <summary>
    /// ClearAllMaterials
    /// </summary>
    public static void ClearAllMaterials()
    {
        _materialDic.Clear();
    }

    /// <summary>
    /// 删除材质
    /// </summary>
    /// <param name="materialPath"></param>
    /// <param name="materialName"></param>
    /// <returns></returns>
    public static void DeleteMaterials(string materialPath, string materialName)
    {
        if (string.IsNullOrWhiteSpace(materialPath) || string.IsNullOrEmpty(materialPath))
        {
            Debug.LogError("材质路径为空");
            return;
        }


        if (string.IsNullOrWhiteSpace(materialName) || string.IsNullOrEmpty(materialName))
        {
            Debug.LogError("材质名字为空");
            return;
        }


        if (_materialDic.ContainsKey(materialName))
        {
            MaterialRes materialRes = _materialDic[materialName];
            if (materialRes.path.Equals(materialPath))
            {
                _materialDic.Remove(materialName);
                return;
            }

            Debug.LogError("非相同路径下的材质，请检查");
        }
        else
        {
            Debug.LogError("删除材质不在缓存里");
        }
    }
}